(function () {
    let currentUserViewIndex = -1;
    let currentUserChpwdIndex = -2;
    let indexInterval = -1;

    function startTokenUpdate() {
        clearInterval(indexInterval);
        updateToken();
        // token更新, 15分钟更新一次
        indexInterval = setInterval(function () {
            updateToken();
        }, 90000);
    }

    function updateToken() {
        $request.get("/oauth/token", function (res) {
            if (res.success) {
                $.cookie("Authorization", res.data.token);
            }
        }).start();
    }

    var token = localStorage.getItem("Authorization");
    if (typeof token != 'undefined' && token != null && token != "") {
        $.cookie("Authorization", token);
        $.cookie("account", localStorage.getItem("account"));
    }
    if (typeof $.cookie("Authorization") == 'undefined' || $.cookie("Authorization") == null || $.cookie("Authorization") == '') {
        window.location.href = Dawn.ctxPath + "/login.html";
    }
    $(".account").text($.cookie("account"));
    $(".user_view").click(function () {
        layer.close(currentUserViewIndex);
        layui.laytpl($("#user_view").html()).render({}, function (html) {
            currentUserViewIndex = layer.open({
                type: 1,
                title: '个人信息',
                area: ['700px', '500px'], //宽高
                content: html,
                success: function () {
                    changeUserInfo();
                }
            });
        });
    });
    $(".user_chpwd").click(function () {
        layer.close(currentUserChpwdIndex);
        layui.laytpl($("#user_chpwd").html()).render({}, function (html) {
            currentUserChpwdIndex = layer.open({
                type: 1,
                title: '修改密码',
                area: ['400px', '400px'],
                content: html,
                success: function () {
                    changeUserPwd();
                }
            });
        });
    })
    $(".logout").click(function () {
        $request.get("/logout", function (res) {
            if (res.success) {
                $.removeCookie("Authorization");
                localStorage.removeItem("Authorization");
                localStorage.removeItem("account");
                window.location.href = Dawn.ctxPath + "/login.html";
            } else {
                Dawn.error(res.message);
            }
        }, function (rdata) {
            Dawn.error(rdata.responseJSON.message);
        }).start();
    });

    function changeUserInfo() {
        $request.get("/system/sysUser/info", function(data) {
            if(data.success) {
                layui.form.val("info", data.data.user);
                layui.laydate.render({
                    elem: "#birthday",
                    value: data.data.user.birthday
                });
                layui.form.render();
                layui.form.on('submit(save)', function (data) {
                    $request.postJson("/system/sysUser/edit", function (res) {
                        if (res.success) {
                            Dawn.success("更新成功!");
                            layui.layer.close(currentUserViewIndex);
                        } else {
                            Dawn.error(res.message);
                        }
                    }).setData(data.field).start();
                    return false;
                });
            } else {
                Dawn.error(data.message);
            }
        }).setAsync(false).start();
    }

    function changeUserPwd() {
        layui.form.verify({
            rePassword: function(value, item){
                let pwd = $("input[name='newPwd']").val();
                if (pwd != value) {
                    return '两次密码输入不一致';
                }
            }
        });
        layui.form.render();
        layui.form.on('submit(save)', function (data) {
            $request.postJson("/system/sysUser/changePwd", function (res) {
                if (res.success) {
                    Dawn.success("修改成功!");
                    layui.layer.close(currentUserChpwdIndex);
                } else {
                    Dawn.error(res.message);
                }
            }).setData(data.field).start();
            return false;
        });
    }

    function renderMenu(id, menu) {
        let html = $("#" + id).html();
        return html.replace("{{name}}", menu.name)
            .replace("{{url}}", menu.url)
            .replace("{{icon}}", menu.icon)
    }

    function renderSingleMenu(menu) {
        return renderMenu("single_menu", menu);
    }

    function renderMoreMenu(menu) {
        let html = renderMenu("more_menu", menu);
        let firstHtml = "";
        for (let j = 0; j < menu.children.length; j++) {
            let children = menu.children[j];
            if (children.children instanceof Array && children.children.length > 0) {
                firstHtml += renderMoreMenu(children);
            } else {
                firstHtml += renderMenu("more_menu_info", children);
            }
        }
        return html.replace("{{html}}", firstHtml);
    }

    $request.get("/system/sysMenu/menus", function (res) {
        if (res.success) {
            let html = "";
            for (let i = 0; i < res.data.length; i++) {
                let menu = res.data[i];
                if (menu.children instanceof Array && menu.children.length > 0) {
                    html += renderMoreMenu(menu);
                } else {
                    html += renderSingleMenu(menu);
                }
            }
            $("#side-menu").append(html);
            startTokenUpdate();
        } else {
            Dawn.error(res.message);
        }
    }, function (rdata) {
        Dawn.error(rdata.responseJSON.message);
    }).setAsync(false).start();
    var height = $("body").height() - $(".content-tabs").height() - $(".border-bottom").height() - 5;
    $("#content-main").css("height", height + "px");
    layui.element.init();
})();